package cn.lijia.itrip.controller;

import cn.lijia.itrip.common.Dto;
import cn.lijia.itrip.common.DtoUtil;
import cn.lijia.itrip.common.ErrorCode;
import cn.lijia.itrip.exception.ItripException;
import cn.lijia.itrip.service.TokenService;
import cn.lijia.itrip.vo.LoginResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 李嘉
 * @create 2018-08-30-10:45
 */
@Controller
@RequestMapping("/api")
public class TokenController {

    @Resource
    private TokenService tokenService;

    @RequestMapping(value = "/retoken",method = RequestMethod.POST)
    @ResponseBody
    public Dto retoken(HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        String userAgent = request.getHeader("user-agent");
        //构建新的token
        try {
            String newToken = tokenService.retoken(token, userAgent);
            //返回对应的数据
            long genTime = System.currentTimeMillis(); //构建时间
            long expTime = genTime + (1000 * 60 * 60 * 2);//过期时间
        return DtoUtil.returnDataSuccess(new LoginResultVO(newToken,genTime,expTime));
        } catch (ItripException e) {
            e.printStackTrace();
           return  DtoUtil.returnFail(e.getMessage(),e.getErrorCode());
        }
    }

}
